import React, { useState, useEffect, useRef } from "react";
import ReactECharts from "echarts-for-react";
import axios from "axios";
import "./Tubiao.css";

export default function Tubiao() {
  const [carData, setCarData] = useState(null);
  const [currentTime, setCurrentTime] = useState(new Date());
  const [wsConnected, setWsConnected] = useState(false);
  const [tableMode, setTableMode] = useState("ev"); // 'ev' 或 'fuel'
  const wsRef = useRef(null);
  const reconnectTimeoutRef = useRef(null);

  // 获取当前时间
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  // 初始化WebSocket连接
  const initWebSocket = () => {
    const wsUrl = "ws://localhost:3005";
    wsRef.current = new WebSocket(wsUrl);

    wsRef.current.onopen = () => {
      console.log("WebSocket连接已建立");
      setWsConnected(true);
    };

    wsRef.current.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.type === "init" || data.type === "update") {
          setCarData(data.data);
        }
      } catch (error) {
        console.error("WebSocket数据解析错误:", error);
      }
    };

    wsRef.current.onclose = () => {
      console.log("WebSocket连接已关闭");
      setWsConnected(false);
      // 断线重连
      reconnectTimeoutRef.current = setTimeout(() => {
        console.log("尝试重新连接WebSocket...");
        initWebSocket();
      }, 3000);
    };

    wsRef.current.onerror = (error) => {
      console.error("WebSocket错误:", error);
    };
  };

  // 初始化数据获取
  useEffect(() => {
    // 获取初始数据
    const fetchData = async () => {
      try {
        const response = await axios.get("http://localhost:3005/jjx/car-data");
        if (response.data.success) {
          setCarData(response.data.data);
        }
      } catch (error) {
        console.error("获取数据失败:", error);
      }
    };

    fetchData();
    initWebSocket();

    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
      if (reconnectTimeoutRef.current) {
        clearTimeout(reconnectTimeoutRef.current);
      }
    };
  }, []);

  // 导出CSV
  const exportCSV = async () => {
    try {
      const response = await axios.get("http://localhost:3005/jjx/export-csv", {
        responseType: "blob",
      });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "car-data.csv");
      document.body.appendChild(link);
      link.click();
      link.remove();
    } catch (error) {
      console.error("导出CSV失败:", error);
    }
  };

  // 导出图片
  const exportImage = async () => {
    try {
      const response = await axios.get(
        "http://localhost:3005/jjx/export-image"
      );
      if (response.data.success) {
        const link = document.createElement("a");
        link.href = response.data.data.image;
        link.setAttribute("download", "car-chart.png");
        document.body.appendChild(link);
        link.click();
        link.remove();
      }
    } catch (error) {
      console.error("导出图片失败:", error);
    }
  };

  // 销售占比饼图配置
  const getSalesShareOption = () => ({
    title: {
      text: "销售占比",
      textStyle: { color: "#fff", fontSize: 16 },
      left: "center",
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c}%",
    },
    legend: {
      orient: "vertical",
      left: "left",
      textStyle: { color: "#fff" },
    },
    series: [
      {
        name: "销售占比",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: "30",
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          {
            value: carData?.salesShare?.fuel || 0,
            name: "油车",
            itemStyle: { color: "#5470c6" },
          },
          {
            value: carData?.salesShare?.ev || 0,
            name: "电车",
            itemStyle: { color: "#91cc75" },
          },
          {
            value: carData?.salesShare?.hybrid || 0,
            name: "混动",
            itemStyle: { color: "#fac858" },
          },
        ],
      },
    ],
  });

  // 销售柱状图配置
  const getSalesChartOption = () => ({
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "10%",
      containLabel: true,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "cross" },
    },
    legend: {
      data: ["销售情况", "车辆价格"],
      textStyle: { color: "#fff" },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: carData?.salesChart?.map((item) => item.name) || [],
      axisLabel: { color: "#fff" },
    },
    yAxis: [
      {
        type: "value",
        name: "销量",
        axisLabel: { color: "#fff" },
      },
      {
        type: "value",
        name: "价格(万元)",
        axisLabel: { color: "#fff" },
      },
    ],
    series: [
      {
        name: "销售情况",
        type: "bar",
        data: carData?.salesChart?.map((item) => item.sales) || [],
        itemStyle: { color: "#5470c6" },
      },
      {
        name: "车辆价格",
        type: "line",
        yAxisIndex: 1,
        data: carData?.salesChart?.map((item) => item.price) || [],
        itemStyle: { color: "#fff" },
      },
    ],
  });

  // 品牌销售饼图配置
  const getBrandSalesOption = () => ({
    // title: {
    //     text: '汽车品牌销售量饼图',
    //     textStyle: { color: '#fff', fontSize: 16 },
    //     left: 'center'
    // },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c}%",
    },
    legend: {
      orient: "vertical",
      left: "left",
      textStyle: { color: "#fff" },
    },
    series: [
      {
        name: "品牌销售",
        type: "pie",
        radius: "50%",
        data:
          carData?.brandSales?.map((item) => ({
            value: item.value,
            name: item.name,
          })) || [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  });

  // 价格分布图配置
  const getPriceDistributionOption = () => ({
    // title: {
    //     text: '车辆销售价格占比',
    //     textStyle: { color: '#fff', fontSize: 16 },
    //     left: 'center'
    // },
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "value",
      axisLabel: { color: "#fff" },
    },
    yAxis: {
      type: "category",
      data: carData?.priceDistribution?.map((item) => item.range) || [],
      axisLabel: { color: "#fff" },
    },
    series: [
      {
        name: "车辆数量",
        type: "bar",
        data: carData?.priceDistribution?.map((item) => item.count) || [],
        itemStyle: { color: "#91cc75" },
      },
    ],
  });

  if (!carData) {
    return <div className="loading">加载中...</div>;
  }

  return (
    <div className="dashboard">
      {/* 头部 */}
      <header className="dashboard-header">
        <div className="header-left">
          <span className="header-title">数据分析</span>
        </div>
        <div className="header-center">
          <h1 className="main-title">汽车数据可视化平台</h1>
        </div>
        <div className="header-right">
          <span className="user-info">用户: admin</span>
          <span className="datetime">
            {currentTime.toLocaleDateString()}{" "}
            {currentTime.toLocaleTimeString()}
          </span>
          <span
            className={`connection-status ${
              wsConnected ? "connected" : "disconnected"
            }`}
          >
            {wsConnected ? "●" : "○"}
          </span>
        </div>
      </header>

      {/* 主要内容区域 */}
      <main className="dashboard-content">
        {/* 上半部分 - 所有组件一行显示 */}
        <div className="upper-section">
          <div className="single-row">
            {/* 电车油车对比表格 */}
            <div className="widget">
              <div className="table-header">
                <h3>电车油车对比 油车/电车</h3>
                <div className="table-toggle">
                  <button
                    className={`toggle-btn ${
                      tableMode === "ev" ? "active" : ""
                    }`}
                    onClick={() => setTableMode("ev")}
                  >
                    电车
                  </button>
                  <button
                    className={`toggle-btn ${
                      tableMode === "fuel" ? "active" : ""
                    }`}
                    onClick={() => setTableMode("fuel")}
                  >
                    油车
                  </button>
                </div>
              </div>
              <div className="table-container">
                <table>
                  <thead>
                    <tr>
                      <th>#</th>
                      <th>车名</th>
                      <th>销量/台</th>
                      <th>能源</th>
                    </tr>
                  </thead>
                  <tbody>
                    {carData.evVsFuel
                      .filter((car) =>
                        tableMode === "ev"
                          ? car.energy === "电动" || car.energy === "混动"
                          : car.energy === "汽油"
                      )
                      .map((car, index) => (
                        <tr key={car.id}>
                          <td>{index + 1}</td>
                          <td>{car.name}</td>
                          <td>{car.sales.toLocaleString()}</td>
                          <td>{car.energy}</td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* 汽车销售词云图 */}
            <div className="widget" >
              <h3>汽车销售词云图</h3>
              <div className="word-cloud">
                {carData.wordCloud.map((word, index) => (
                  <span
                    key={index}
                    className="word-cloud-item"
                    style={{
                      fontSize: `${word.value / 10 + 12}px`,
                      opacity: word.value / 100,
                    }}
                  >
                    {word.name}
                  </span>
                ))}
              </div>
            </div>

            {/* 车辆总数据 */}
            <div className="widget">
              <h3>车辆总数据</h3>
              <div className="summary-stats">
                <div className="stat-item">
                  <div className="stat-value">
                    {carData.summary.totalVehicles}
                  </div>
                  <div className="stat-label">车辆总数据</div>
                </div>
                <div className="stat-item">
                  <div className="stat-value">
                    {carData.summary.bestSellingCar}
                  </div>
                  <div className="stat-label">销量最多汽车</div>
                </div>
                <div className="stat-item">
                  <div className="stat-value">
                    {carData.summary.highestSales.toLocaleString()}辆
                  </div>
                  <div className="stat-label">车辆最高销售额</div>
                </div>
                <div className="stat-item">
                  <div className="stat-value">
                    {carData.summary.bestSellingType}
                  </div>
                  <div className="stat-label">销售最多车型</div>
                </div>
                <div className="stat-item">
                  <div className="stat-value">
                    {carData.summary.bestSellingBrand}
                  </div>
                  <div className="stat-label">车型最多品牌</div>
                </div>
                <div className="stat-item">
                  <div className="stat-value">
                    {carData.summary.averagePrice}万
                  </div>
                  <div className="stat-label">车辆平均价格</div>
                </div>
              </div>

              {/* 品牌排行榜和油电销售占比一行 */}
              <div className="brand-share-row">
                {/* 汽车品牌销售排行榜 */}
                <div className="brand-ranking-section">
                  <h4>汽车品牌销售排行榜</h4>
                  <div className="brand-ranking">
                    {carData.brandRanking.map((brand) => (
                      <div key={brand.rank} className="brand-item">
                        <span className="brand-rank">No.{brand.rank}</span>
                        <span className="brand-name">{brand.name}</span>
                        <span className="brand-categories">
                          {brand.categories}类
                        </span>
                      </div>
                    ))}
                  </div>
                </div>

                {/* 油电销售占比 */}
                <div className="sales-share-section">
                  <h4>油电销售占比</h4>
                  <ReactECharts
                    option={getSalesShareOption()}
                    style={{ height: "250px" }}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className="upper-section">
          <div className="double-row">
            {/* 汽车品牌销售量饼图 */}
            <div className="widget">
              <h3>汽车品牌销售量饼图</h3>
              <ReactECharts
                option={getBrandSalesOption()}
                style={{ height: "400px"}}
              />
            </div>

            {/* 车辆销售价格占比 */}
            <div className="widget">
              <h3>车辆销售价格占比</h3>
              <ReactECharts
                option={getPriceDistributionOption()}
                style={{ height: "400px" }}
              />
            </div>
          </div>
        </div>

        {/* 下半部分 */}
        <div className="lower-section">
          {/* 汽车排行榜 */}
          <div className="widget">
            <h3>汽车排行榜</h3>
            <div className="ranking-list">
              {carData.carRanking.map((car) => (
                <div key={car.rank} className="ranking-item">
                  <div className="rank-number">{car.rank}</div>
                  <div className="car-image">
                    <img src={car.image} alt={car.name} />
                  </div>
                  <div className="car-info">
                    <div className="car-name">{car.name}</div>
                    <div className="car-brand">{car.brand}</div>
                    <div className="car-price">{car.price}</div>
                    <div className="car-sales">
                      销量: {car.sales.toLocaleString()}
                    </div>
                    <div className="car-warranty">保修: {car.warranty}</div>
                    <div className="car-launch">上市: {car.launchDate}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 汽车销售柱状统计图 */}
          <div className="widget">
            <h3
              style={{
                textAlign: "center",
                marginBottom: "10px",
                height: "5%",
              }}
            >
              汽车销售柱状统计图
            </h3>
            <ReactECharts
              option={getSalesChartOption()}
              style={{ height: "95%" }}
            />
          </div>
        </div>
      </main>

      {/* 导出按钮 */}
      <div className="export-buttons">
        <button onClick={exportCSV} className="export-btn">
          导出CSV
        </button>
        <button onClick={exportImage} className="export-btn">
          导出图片
        </button>
      </div>
    </div>
  );
}
